package com.xyhuo.leetcode.november;

/**
 * 整数反转
 * https://leetcode.cn/problems/reverse-integer/
 *
 * @time 2023/11/28
 */
public class Reverse {

    public int reverse(int x) {
        if (x == 0) {
            return 0;
        }
        int pre = 1;
        if (x < 0) {
            pre = -1;
            if (x == -2147483648) {
                return 0;
            }
            x = -1 * x;
        }
        String xStr = String.valueOf(x);
        char[] charArray = xStr.toCharArray();
        StringBuilder sb = new StringBuilder();
        if (pre < 0) {
            sb.append("-");
        }
        int length = charArray.length;
        for (int i = 0; i < length; i++) {
            sb.append(charArray[length - 1 - i]);
        }
        String strNum = sb.toString();
        if (pre < 0 && strNum.length() >= 11 && strNum.compareTo("-2147483648") > 0) {
            return 0;
        }
        if (pre > 0 && strNum.length() >= 10 && strNum.compareTo("2147483647") > 0) {
            return 0;
        }
        return Integer.parseInt(strNum);
    }

//    public static void main(String[] args) {
//        Reverse reverse = new Reverse();
//        reverse.reverse(-123);
//    }
}
